﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using GUESTSMANAGEMENT.Controller;
using Coolite.Ext.Web;


namespace GUESTSMANAGEMENT.View.Event
{
    public partial class frmEvent : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public Store GridStore
        {
            get;
            set;
        }


        protected void FormSave(object sender, AjaxEventArgs e)
        {            
            try
            {
                string id = this.txt_eventId.Text;
                gmevent temp = Controller.Event.getByEventDate(this.eventDate.SelectedDate);
                if (true)
                {
                    if (id.Equals(""))
                    {
                        using (guestsmanagementEntities context = new guestsmanagementEntities())
                        {
                            gmevent evento = new gmevent();
                            evento.NMEVENT = this.eventName.Text.ToString();
                            evento.DTEVENT = this.eventDate.SelectedDate;
                            evento.DSEVENT = this.eventDescription.Text.ToString();
                            evento.QTBF = int.Parse(this.Nqtbf.Text);
                            evento.QTBM = int.Parse(this.Nqtbm.Text);
                            evento.QTFF = int.Parse(this.Nqtff.Text);
                            evento.QTFM = int.Parse(this.Nqtfm.Text);
                            evento.TMLIST = TimeSpan.Parse(eventTime.SelectedItem.Value.ToString());
                            evento.TMEXPIRE = TimeSpan.Parse(timeExpire.SelectedItem.Value.ToString());
                            
                            int FileLen = this.FileUploadField1.PostedFile.ContentLength;
                            if (FileLen > 0)
                            {
                                evento.NMPATH = this.FileUploadField1.PostedFile.FileName;
                                evento.FLSIZE = FileLen;
                                byte[] arrFile = new byte[FileLen];
                                Stream objStream = this.FileUploadField1.PostedFile.InputStream;
                                objStream.Read(arrFile, 0, FileLen);
                                objStream.Close();
                                evento.FLEVENT = arrFile;
                            }
                            this.winEvent.Hide();

                            Controller.Event.addEvent(evento);
                            ClearWindow(Controls);
                            this.GridStore.AddScript(string.Format("{0}.reload();", this.GridStore.ClientID));
                            FormStatusBar.SetStatus(new StatusBarStatusConfig { Text = "Cadastro efetuado com sucesso!", IconCls = "", Clear2 = true });
                        }
                    }
                    else
                    {
                        using (guestsmanagementEntities context = new guestsmanagementEntities())
                        {
                            gmevent evento = Controller.Event.getByEvent(int.Parse(id));

                            /*Atualiza dados dos relacionados*/
                            var selectListGuests = from eventUser in context.gmeventuser.Include("gmuser.nmuser")
                                                   from gevent in context.gmevent.Include("gmevent.nmevent")
                                                   from user in context.gmuser.Include("gmuser.nmuser")
                                                   where evento.CDEVENT == gevent.CDEVENT && gevent.CDEVENT == eventUser.gmevent.CDEVENT && user.CDUSER == eventUser.gmuser.CDUSER
                                                   select new { eventUser.CDEVENTUSER, gevent.CDEVENT, user.NMUSER, user.CDUSER, gevent.NMEVENT, eventUser.QTBF, eventUser.QTBM, eventUser.QTFF, eventUser.QTFM };


                            foreach (var relation in selectListGuests)
                            {
                                gmeventuser rel = Controller.EventUser.getByEventUser((int)relation.CDEVENTUSER);
                                
                                if (relation.QTBF == evento.QTBF)
                                {
                                    rel.QTBF = int.Parse(this.Nqtbf.Text);
                                }
                                if (relation.QTBM == evento.QTBM)
                                {
                                    rel.QTBM = int.Parse(this.Nqtbm.Text);
                                }
                                if (relation.QTFF == evento.QTFF)
                                {
                                    rel.QTFF = int.Parse(this.Nqtff.Text);
                                }
                                if (relation.QTFM == evento.QTFM)
                                {
                                    rel.QTFM = int.Parse(this.Nqtfm.Text);
                                }
                                Controller.EventUser.updateEventUser(rel);
                            }
                            
                            
                            evento.NMEVENT = this.eventName.Text.ToString();
                            evento.DTEVENT = this.eventDate.SelectedDate;
                            evento.DSEVENT = this.eventDescription.Text.ToString();
                            evento.QTBF = int.Parse(this.Nqtbf.Text);
                            evento.QTBM = int.Parse(this.Nqtbm.Text);
                            evento.QTFF = int.Parse(this.Nqtff.Text);
                            evento.QTFM = int.Parse(this.Nqtfm.Text);
                            evento.TMLIST = TimeSpan.Parse(eventTime.SelectedItem.Value.ToString());
                            evento.TMEXPIRE = TimeSpan.Parse(timeExpire.SelectedItem.Value.ToString());
                            
                            int FileLen = this.FileUploadField1.PostedFile.ContentLength;
                            if (FileLen > 0)
                            {
                                evento.NMPATH = this.FileUploadField1.PostedFile.FileName;
                                evento.FLSIZE = FileLen;
                                byte[] arrFile = new byte[FileLen];
                                Stream objStream = this.FileUploadField1.PostedFile.InputStream;
                                objStream.Read(arrFile, 0, FileLen);
                                objStream.Close();
                                evento.FLEVENT = arrFile;
                            }
                            
                            

                            Controller.Event.updateEvent(evento);
                            this.winEvent.Hide();

                            ClearWindow(Controls);
                            this.GridStore.AddScript(string.Format("{0}.reload();", this.GridStore.ClientID));
                            Ext.Msg.Alert("Alerta!", "Evento <br>" + evento.NMEVENT + " </br> atualizado com sucesso!").Show();
                            FormStatusBar.SetStatus(new StatusBarStatusConfig { Text = "Evento atualizado com sucesso!", IconCls = "", Clear2 = true });

                        }
                    }
                }
                else
                {
                    Ext.Msg.Alert("Alerta!", "A data já possui o evento: <br> <b>" + temp.NMEVENT + "</b>").Show();
                }
            }
            catch
            {
                Ext.Msg.Alert("Alerta!", "Ocorreu um erro durante a transação! Tente novamente!").Show();
            }
            }

        public void ShowEvent()
        {
            this.winEvent.Show();
        }

        public void SetEvent(gmevent evento)
        {
            this.txt_eventId.Text = evento.CDEVENT.ToString();
            this.eventName.Text = evento.NMEVENT;
            this.eventDate.SelectedDate = Convert.ToDateTime(evento.DTEVENT);
            this.eventDescription.Text = evento.DSEVENT;
            this.Nqtbf.Text = evento.QTBF.ToString();
            this.Nqtbm.Text = evento.QTBM.ToString();
            this.Nqtff.Text = evento.QTFF.ToString();
            this.Nqtfm.Text = evento.QTFM.ToString();
            //this.FileUploadField1.Text = evento.NMPATH.ToString();
            eventTime.SelectedTime = TimeSpan.Parse(evento.TMLIST.ToString());
            timeExpire.SelectedTime = TimeSpan.Parse(evento.TMEXPIRE.ToString());
        }

        protected void Close(object sender, AjaxEventArgs e)
        {
            this.winEvent.Hide();
            ClearWindow(Controls);
        }

        public void ClearWindow(ControlCollection AllControls)
        {
            
            foreach (Control c in AllControls)
            {
                if (c is TextField)
                {
                    ((TextField)c).Text = "";
                }
                if (c is ComboBox)
                {
                    ((ComboBox)c).SetValue("");
                }
                if (c is Checkbox)
                {
                    ((Checkbox)c).Checked = true;
                }
                if (c is DateField)
                {
                    ((DateField)c).SetValue("");
                }
                if (c is TextArea)
                {
                    ((TextArea)c).Text = "";
                    ((TextArea)c).Visible = false;
                }
                if (c is Hidden)
                {
                    ((Hidden)c).Text = "";
                }
                if (c is NumberField)
                {
                    ((NumberField)c).Text = "";
                }
                
                /*if (c is FileUploadField)
                {
                    ((FileUploadField)c).Text = "";
                }*/
                

                this.winEvent.Restore();
                ClearWindow(c.Controls);
            }
        }
    }
}